import { getRouters } from '@/api/menus'
import { constantRoutes } from '@/router'
import Layout from '@/layout/index.vue'

const permissions = {
  state: {
    sideBarRouters: []
  },
  mutations: {
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sideBarRouters = routers
    }
  },
  actions: {
    GenerateRoutes ({ commit, state }) {
      return new Promise(resolve => {
        getRouters().then(res => {
          const rData = JSON.parse(JSON.stringify(res.data))
          const sData = JSON.parse(JSON.stringify(res.data))

          const rewriteRoutes = filterAsyncRouter(rData)
          const sidebarRoutes = filterAsyncRouter(sData)

          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          // commit('SET_SIDEBAR_ROUTERS', res.data)
          resolve(rewriteRoutes)
        })
      })
    }
  }
}

function filterAsyncRouter (asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // 排除layout的情况,layout不是放在views文件夹下
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }

    if (route.children !== null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }

    return true
  })
}

function loadView (view) {
  // 其他方式
  // return () => require(['@/views' + view + '.vue'])
  // return () => import(`@/views/${view}.vue`)
  // return (resolve) => require([`@/views/${view}`], resolve)
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permissions
